package com.xm.queue.task2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 任务线程池
 */
@Slf4j
public class TaskExecutor {
    private TaskExecutor() {
    }

    public static final int CPU_CORES;// 最大核心线程数
    public static final int CORE_POOL_SIZE;// 核心线程数
    private static final int MAXIMUM_POOL_SIZE;// 最大线程数
    private static final long KEEP_ALIVE_TIME = 60L;// 存活时间
    private static final int CAPACITY = 500;// 队列最大容量
    static {
        CPU_CORES = Runtime.getRuntime().availableProcessors();
        CORE_POOL_SIZE = CPU_CORES / 2;
        MAXIMUM_POOL_SIZE = CORE_POOL_SIZE + 2;
    }

    /**
     * 线程池
     */
    private static final ExecutorService SERVICE = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAXIMUM_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(CAPACITY),
            new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * 执行单个任务
     * @param task 实现 Runnable 接口的任务
     */
    public static void submit(Runnable task) {
        SERVICE.submit(task);
    }

    /**
     * 关闭线程池
     */
    public static void shutdown() {
        log.info("正在关闭线程池资源...");
        try {
            SERVICE.shutdown();
            if (!SERVICE.awaitTermination(5, TimeUnit.SECONDS)) {
                SERVICE.shutdownNow();
                log.info("已关闭线程池资源！");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
